package com.project.service.impl;

import com.project.bean.CutPageBean;
import com.project.bean.UserBean;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.ibatis.session.SqlSession;

import java.lang.invoke.VarHandle;
import java.util.List;

/**
 * 用户业务实现类
 */
public class UserServiceImpl extends BaseService implements IUserService {
    @Override
    public boolean add(UserBean user) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        if (mapper.findByUserName(user.getUserName())!=null){
            session.close();
            return false;
        }
        mapper.add(user);
        session.commit();
        session.close();
        return true;
    }

    @Override
    public void del(Integer userId) {
            SqlSession session = this.getSession();
            IUserMapper mapper = session.getMapper(IUserMapper.class);
            mapper.del(userId);
            session.commit();
            session.close();
    }

    @Override
    public void updatePwd(Integer userId, String newPassword) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.updatePwd(userId,newPassword);
        session.commit();
        session.close();
    }

    @Override
    public void updateGrade(Integer userId, String newGrade) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.updateGrade(userId,newGrade);
        session.commit();
        session.close();
    }

    @Override
    public UserBean login(String userName, String password) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        UserBean user = mapper.login(userName, password);
        session.close();
        return user;
    }

    @Override
    public UserBean findById(Integer userId) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        UserBean user = mapper.findById(userId);
        session.close();
        return user;
    }

    @Override
    public CutPageBean<UserBean> cutAll(Integer pageNO) {
        CutPageBean<UserBean> cutPageBean = new CutPageBean<>();
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        List<UserBean> list = mapper.cutByList((pageNO - 1) * CutPageBean.PAGESIZE, CutPageBean.PAGESIZE);
        cutPageBean.setList(list);
        cutPageBean.setCount(mapper.getTotal());
        session.close();
        return cutPageBean;
    }
}
